package com.nowcoder.community.c_service;

import com.nowcoder.community.z_util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class LikeService {

    @Autowired
    private RedisTemplate redisTemplate;

    //显示赞的status
    public void addLike(int userId, int entityType, int entityId, int entityUserId){

        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                //存2个redis。一个是主点赞行entity，另一个是每个用户的的点赞数
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
                //因为涉及2个表，所以要加事务

                boolean isMember = redisOperations.opsForSet().isMember(entityLikeKey, userId);


                //开始准备入队列(分为点了+，再点-即存在userid就remove)
                redisOperations.multi();

                if(isMember){
                    redisOperations.opsForSet().remove(entityLikeKey,userId);
                    redisOperations.opsForValue().decrement(userLikeKey);
                }else {
                    redisOperations.opsForSet().add(entityLikeKey, userId);
                    redisOperations.opsForValue().increment(userLikeKey);
                }
                //结束提交

                System.out.println(redisOperations.opsForSet().members(entityLikeKey));
                return redisOperations.exec();
            }
        });
    }


    //显示该帖子总点赞
    public Long findEntityLikeCount(int entityType, int entityId) {
        String k = RedisKeyUtil.getEntityLikeKey(entityType,entityId);
        return redisTemplate.opsForSet().size(k);
    }
    //查看已赞，or未赞 返回code状态码
    public int findEntityLikeStatus(int userId, int entityType, int entityId) {
        String k = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().isMember(k, userId) ? 1 : 0;
    }
    //显示1、2级回复的某用户？获得的赞的个数
    public int findUserLikeCount(int userId) {
        String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
        Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
        return count == null ? 0 : count.intValue();
    }
}
